<?php 
Import::appLibs("Configuration");
class PostController extends Controller {
	public function __construct(){
		$this->calledClass(get_class($this));
	}
	public function post(){
		$post = $this->loadModel("Post");
		//$records = $employer->getList($page=1,$perpage=20,$search="",$searchFields=array(),$sortFields=array(),$sortCriteria="");
		$page = $this->get("page")!=NULL?$this->get("page"):1;
		$perpage = $this->get("perpage")!=NULL?$this->get("perpage"):20;
		$search = $this->get("search")!=NULL?$this->get("search"):"";
		$records = $post->getList($page,$perpage,$search,array("emp_id","post_date","created"),array());
		$this->set(array("records"=>$records));
		$this->render("admin_display");
	}
	
	/*
	* insert
	* edit
	* update
	* delete
	*  */
	public function DisplayAdmin(){
		$post = $this->loadModel("Post");
		$category=$this->loadModel("Categorie");
		$query = $post->queryJoinTable();
		$this->set(array("jobClass"=>$post->CountCategoriesFunction(23)));
		$this->set(array("jobClassCountNameCate"=>$post->getCountNameCategory(23)));
		$this->set(array("jobType"=>$post->CountCategoriesFunction(20)));
		$this->set(array("location"=>$post->CountCategoriesFunction(1)));
		$this->set(array("locationCountNameCate"=>$post->getCountNameCategory(1)));
		$this->set(array("jobcategory"=>$category->GetJobTime(23)));
		$this->set(array("getAllCategory"=>$post->getALLCategory()));
		$this->set(array("list"=>$post->DisplayAdmin($query,$this->get("page"),$this->get("perpage")?$this->get("perpage"):20,array("job_categories"=>$this->get("jobcat"),"title"=>$this->get("jobtitle"),"location"=>$this->get("joblocation"),"job_time"=>$this->get("jobtype")),array("post_date"),"DESC","AND")));
		$this->set(array("urls"=>array("jobcat"=>$this->get("jobcat"),"jobtitle"=>$this->get("jobtitle"),"joblocation"=>$this->get("joblocation"),"jobtype"=>$this->get("jobtype"))));
		$this->set(array("getPost"=>$post->GetPost()));
		$this->render("admin");
	}
	public function DisplayFront(){
		$post = $this->loadModel("Post");
		$category=$this->loadModel("Categorie");
		$query = $post->QueryFront(Session::get("candidate_id"));
		$this->set(array("location"=>$category->GetJobTime(1)));
		$this->set(array("jobcategory"=>$category->GetJobTime(23)));
		$this->set(array("jobType"=>$category->GetJobTime(20)));
		$this->set(array("list"=>$post->PaginationFront($query,$this->get("page"),$this->get("perpage")?$this->get("perpage"):20,array("job_categories"=>$this->get("jobcat"),"title"=>$this->get("jobtitle"),"location"=>$this->get("joblocation"),"job_time"=>$this->get("jobtype")),array("created"),"DESC","AND")));
		$this->set(array("urls"=>array("job_category"=>$this->get("jobcat"),"title"=>$this->get("jobtitle"),"location"=>$this->get("joblocation"),"job_type"=>$this->get("jobtype"))));
		$this->set(array("getPost"=>$post->GetPostByEmpId(Session::get("candidate_id"))));
		///get emp_id from url and set back to view
		$this->set(array("emp_id"=>Session::get("candidate_id")));
		$this->set(array("layout"=>"job"));
		$this->render("admin");
	}
	public function SaveEdit(){
		if(isset($_POST["bntSaveEdit"])){
			$post = $this->loadModel("Post");
			$job=$this->loadModel("Job");
			$currency = $this->loadModel("Currency");
			if(isset($_POST["checkbox"])){
				$checkedbox = $this->get("checkbox");
				$empId = $this->get("empId");
				$title = ucwords(trim($this->get("txtTitle")));
			    $by_company= ucwords(trim($this->get("txtPostBy")));
			    $num_hire= ucwords(trim($this->get("txtHire")));
			    $job_time= ucwords(trim($this->get("cboJobTime")));
			    $location= ucwords(trim($this->get("cboLocation")));
			    $qualification= ucwords(trim($this->get("txtqual")));
			    $job_categories= ucwords(trim($this->get("cboJobCategory")));
			    $gender= ucwords(trim($this->get("txtgender")));
			    $age= ucwords(trim($this->get("txtage")));
			    $post_date= trim($this->get("dtpPostDate"));
			    $expire_date= trim($this->get("dtpDeadline"));
			    $profile= ucwords(trim($this->get("txtprofile")));
			    $description= ucwords(trim($this->get("txtdescription")));
			    $education= ucwords(trim($this->get("txtaEducation")));
			    $competencies= ucwords(trim($this->get("txtkeycompetencies")));
			    $apply= ucwords(trim($this->get("txtapply")));
			    $contact_person= ucwords(trim($this->get("txtContact")));
			    $telephone= trim($this->get("txtTelephone"));
			    $email= trim($this->get("txtEmail"));
			    $website= trim($this->get("txtWebsite"));
				$counts = count($empId);
				if($checkedbox){
					for ($i=0; $i < $counts; $i++){
						$getfieldpost=$post->findObject(array("job_id="=>$checkedbox));
						$data = $post->version("Posts","version",array("id="=>$getfieldpost->id));
						$version = $data + 1;
						$job->edit(array("emp_id"=>$empId[$i],
										 "title"=>$title,
										 "by_company"=>$by_company,
										 "num_hire"=>$num_hire,
										 "job_time"=>$job_time,
										 "location"=>$location,
										 "qualification"=>$qualification,
										 "job_categories"=>$job_categories,
										 "gender"=>$gender,
										 "age"=>$age,
										 "post_date"=>$post_date,
										 "expire_date"=>$expire_date,
										 "profile"=>$profile,
										 "description"=>$description,
										 "education"=>$education,
										 "competencies"=>$competencies,
										 "apply"=>$apply,
										 "contact_person"=>$contact_person,
										 "telephone"=>$telephone,
										 "email"=>$email,
										 "website"=>$website,
									     "modify"=>date("Y-m-d H:i:s"),
										 "version"=>$version),array("id="=>$checkedbox));
					}
					$this->DisplayAdmin();
				}
			}else {
				$this->DisplayAdmin();
			}
		}
	}
	public function delete(){
		$post = $this->loadModel("Post");
			$checkedbox = $this->get("id");
			if($checkedbox){
				$post->delete(array($checkedbox),true);
				$this->DisplayAdmin();
			}else {
			$this->DisplayAdmin();
		}
	}
	public function GetField(){
		$job = $this->loadModel("Job");
		$post= $this->loadModel("Post");
			$checkedbox = $this->get("pid");
			if($checkedbox){
				$getfieldpost=$post->findObject(array("id="=>$checkedbox));
				$query = $post->QueryGetField();
				$getfield[] = $post->GetFieldWithMultiTable($query,array("Jobs.id="=>$getfieldpost->job_id));
				$this->set(array("getfield"=>$getfield));
				$category = $this->loadModel("Categorie");
				$post= $this->loadModel("Post");
				$this->set(array("list"=>$post->QueryEmp()));
				$this->set(array("jobtime"=>$category->GetJobTime(20)));
				$this->set(array("location"=>$category->GetJobTime(1)));
				$this->set(array("jobcategory"=>$category->GetJobTime(23)));
				$this->set(array("industry"=>$category->GetJobTime(179)));
				$this->set(array("companytype"=>$category->GetJobTime(227)));
				$this->set(array("months"=>$category->GetJobTime(287)));
				$this->set(array("days"=>$category->GetJobTime(255)));
				$this->set(array("layout"=>"edit"));
				$this->render("admin");
			}else {
			$this->render("admin_edit_post");
		}
	}
	public function ActionAll(){
		if(isset($_POST["btn_approveAll"])){
			$post = $this->loadModel("Post");
			$job = $this->loadModel("Job");
			$membership = $this->loadModel("Membership");
			$candidate = $this->loadModel("Candidate");
			$category = $this->loadModel("Categorie");
			if(isset($_POST["checkbox"])){
				$checkedbox = $this->get("checkbox");
				$counts = count($checkedbox);
				if($checkedbox){
					for ($i=0; $i < $counts; $i++){
						$dds = $checkedbox[$i];
						$getDataUpdate = $post->edit(array("approve"=>1),array("id="=>$dds));
						$getRecord = $job->findObject(array("id = "=>$getDataUpdate->job_id));
						$getObjects = $membership->getObject(array("user_id","cat_id"),array("cat_id="=>$getRecord->job_categories,"sub_type="=>"Candidate"));
						foreach ($getObjects as $getObject){
							$getMails[] = $candidate->findObject(array("id = "=>$getObject->user_id));
						}
						if($getObjects){
							//getCategoriesAsArray
							$getCategories = $category->findObject(array("id = "=>$getRecord->job_categories));
							//if($getRecord->job_categories == $getCategories->id)
							$str = "<b>Your HRCambodia.com Daily Job Alert</b><br/>";
							$str .="<span style='font-family: Trebuchet MS;padding-right:5px'>" . $getDataUpdate->post_date ."</span>";
							$str .="<a style='font-family: Trebuchet MS;padding-right:5px' href='http://".$_SERVER['HTTP_HOST']."/demo/job/detail/id:".$getRecord->id."'>". $getRecord->title ."</a>";
							$str .="<span style='font-family: Trebuchet MS'>" . $getCategories->name ."</span>";
							//send mail to employer after updated status
							ob_start();
							//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
							Import::util('class.phpmailer');
							//the true param means it will throw exceptions on errors, which we need to catch
							$mail = new PHPMailer(true);
							//telling the class to use SMTP
							$mail->IsSMTP();
							try {
								// SMTP server
								$mail->Host = "mail.atmos-techno.com";
								// enables SMTP debug information (for testing),  show debug : SMTPDebug  = 2,  Hide debug : SMTPDebug  = 1
								$mail->SMTPDebug = 1;
								// enable SMTP authentication
								$mail->SMTPAuth = true;
								// sets the SMTP server
								$mail->Host = "mail.atmos-techno.com";
								// set the SMTP port for the MY OWN DOMAIN server
								$mail->Port = 26;
								// SMTP account username
								$mail->Username = "demo@atmos-techno.com";
								// SMTP account password
								$mail->Password = "demo*123456";
								//$mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
								//$mail->AddAddress('physopheak10@gmail.com', '');
								//$mail->AddAddress('phonpisey23@gmail.com','');
								foreach($getMails as $getMail){
									$email_address = filter_input(INPUT_GET, $getMail->email, FILTER_VALIDATE_EMAIL);
								}
								if (!$email_address) {
									$mail->SetFrom('demo@atmos-techno.com', 'HRCambodia');
									// $mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
									foreach($getMails as $getMail){
										$mail->AddAddress($getMail->email, ' ');
									}
									//$mail->AddAddress('phonpisey23@gmail.com','');
									$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
									$mail->Subject = "Request Quote Information";
									// optional - MsgHTML will create an alternate automatically
									$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
									$mail->MsgHTML("<h3>Request Quote Information</h3>" . $str . "<br/>");
									$mail->Send();
									//echo "your comment has been send !!.";
									//redirect to home page of hekconstruntion.com
									$this->redirect(array("com"=>"post","action"=>"displayadmin"));
							} else {
								echo 'Email is invalid...';
								break;
							}
							} catch (phpmailerException $e) {
								//Pretty error messages from PHPMailer
								echo $e->errorMessage();
							} catch (Exception $e) {
								//Boring error messages from anything else!
								echo $e->getMessage();
							}
						}
					}
					$this->DisplayAdmin();
				}
			}else {
				$this->DisplayAdmin();
			}
		}
		if(isset($_POST["btn_disapproveAll"])){
			$post = $this->loadModel("Post");
			if(isset($_POST["checkbox"])){
				$checkedbox = $this->get("checkbox");
				$counts = count($checkedbox);
				if($checkedbox){
					for ($i=0; $i < $counts; $i++){
						$dds = $checkedbox[$i];
						$post->edit(array("approve"=>0),array("id="=>$dds));
					}
					$this->DisplayAdmin();
				}
			}else {
				$this->DisplayAdmin();
			}
		}
	}
	
	public function FrontSubscriptionExpire(){
		$this->render("front_subscription_expire");
	}
	public function DisplayAdminPostWaiting(){
		$post = $this->loadModel("Post");
		$this->set(array("jobClass"=>$post->CountCategoriesFunction(23)));
		$this->set(array("jobClassCountNameCate"=>$post->getCountNameCategory(23)));
		$this->set(array("jobType"=>$post->CountCategoriesFunction(20)));
		$this->set(array("location"=>$post->CountCategoriesFunction(1)));
		$this->set(array("locationCountNameCate"=>$post->getCountNameCategory(1)));
		$this->set(array("getAllCategory"=>$post->getALLCategory()));
		$query = $post->queryPostApprove(0);
		$this->set(array("list"=>$post->DisplayAdminWithoutWhere($query,$this->get("page"),$this->get("perpage")?$this->get("perpage"):20,array("job_categories"=>$this->get("jobclass"),"location"=>$this->get("joblocation"),"type"=>$this->get("jobtype")),array("post_date"),"DESC","AND")));
		$this->set(array("layout"=>"postwaiting"));
		$this->render("admin");
	}
	public function DisplayAdminNonApprovePost(){
		$post = $this->loadModel("Post");
		$this->set(array("jobClass"=>$post->CountCategoriesFunction(23)));
		$this->set(array("jobClassCountNameCate"=>$post->getCountNameCategory(23)));
		$this->set(array("jobType"=>$post->CountCategoriesFunction(20)));
		$this->set(array("location"=>$post->CountCategoriesFunction(1)));
		$this->set(array("locationCountNameCate"=>$post->getCountNameCategory(1)));
		$this->set(array("getAllCategory"=>$post->getALLCategory()));
		$query = $post->queryPostApprove(0);
		$this->set(array("list"=>$post->DisplayAdminWithoutWhere($query,$this->get("page"),$this->get("perpage")?$this->get("perpage"):20,array("job_categories"=>$this->get("jobclass"),"location"=>$this->get("joblocation"),"type"=>$this->get("jobtype")),array("post_date"),"DESC","AND")));
		$this->set(array("layout"=>"noneapproved"));
		$this->render("admin");
	}
	public function addNew(){
		$category = $this->loadModel("Categorie");
		$post= $this->loadModel("Post");
		$this->set(array("list"=>$post->QueryEmp()));
		$this->set(array("jobtime"=>$category->GetJobTime(20)));
		$this->set(array("location"=>$category->GetJobTime(1)));
		$this->set(array("jobcategory"=>$category->GetJobTime(23)));
		$this->set(array("industry"=>$category->GetJobTime(179)));
		$this->set(array("companytype"=>$category->GetJobTime(227)));
		$this->set(array("months"=>$category->GetJobTime(287)));
		$this->set(array("days"=>$category->GetJobTime(255)));
		$this->set(array("layout"=>"addnew"));
		$this->render("admin");
	}
	public function SavePost(){	
		$post = $this->loadModel("Post");
		$job= $this->loadModel("Job");
		$empIds = $this->get("empId");
		$yearPostDate = $this->get('dtpPostDate');
		$monthPostDate = $this->get("monthPostdate");
		$dayPostDate = $this->get('dayPostDate');
		$arrPostDate  = array("$yearPostDate","$monthPostDate","$dayPostDate");
		$postDate= implode("-", $arrPostDate);
		$yearDeadLine = $this->get('dtpDeadLine');
		$monthDeadLine = $this->get("monthDeadLine");
		$dayDeadLine = $this->get('dayDeadLine');
		$arrDeadLine  = array("$yearDeadLine","$monthDeadLine","$dayDeadLine");
		$deadLine= implode("-", $arrDeadLine);
		if(isset($_POST["btnAdd"])){
				foreach ($empIds as $empId){
				$jobId = $job->save(array(
					    "emp_id"=>$empId,
					    "title"=>ucwords(trim($this->get("txtTitle"))),
					    "by_company"=>ucwords(trim($this->get("txtPostBy"))),
					    "num_hire"=>ucwords(trim($this->get("txtHire"))),
					    "job_time"=>ucwords(trim($this->get("cboJobTime"))),
					    "location"=>ucwords(trim($this->get("cboLocation"))),
					    "qualification"=>ucwords(trim($this->get("txtqual"))),
					    "job_categories"=>ucwords(trim($this->get("cboJobCategory"))),
					    "gender"=>ucwords(trim($this->get("txtgender"))),
					    "age"=>ucwords(trim($this->get("txtage"))),
					    "post_date"=>trim($postDate ." ". date("H:i:s")),
					    "expire_date"=>trim($deadLine ." ". date("H:i:s")),
					    "profile"=>ucwords(trim($this->get("txtprofile"))),
					    "description"=>ucwords(trim($this->get("txtdescription"))),
					    "education"=>ucwords(trim($this->get("txtaEducation"))),
					    "competencies"=>ucwords(trim($this->get("txtkeycompetencies"))),
					    "apply"=>ucwords(trim($this->get("txtapply"))),
					    "contact_person"=>ucwords(trim($this->get("txtContact"))),
					    "telephone"=>trim($this->get("txtTelephone")),
					    "email"=>trim($this->get("txtEmail")),
					    "website"=>trim($this->get("txtWebsite")),
					    "version"=>1,
					    "created"=>date("y-m-d h:m:S")
					  ));
					$post->save(array(
						"job_id"=>$jobId->id,
						"emp_id"=>$empId,
						"post_date"=>date("Y-m-d H:i:s"),
						"type"=>$this->get("posttype"),
						"approve"=>$this->get("approve"),
						"version"=>1,
						"created"=>date("Y-m-d H:i:s")));
					$this->addNew();
				}
			}else{
				$this->addNew();
			}
		}
}
?>